<template>
  <a-modal
    v-model:open="visible"
    title="参与申报"
    class="participateModal"
    destroyOnClose
    :width="500"
    :maskClosable="false"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      layout="inline"
      :labelCol="labelCol"
    >
      <a-form-item label="需求计划名称" name="planName">
        <a-input
          v-model:value="form.planName"
          class="formInput"
          placeholder="2025年6月25日需求响应"
          :disabled="true"
        />
      </a-form-item>

      <a-form-item label="需求类型" name="demandType">
        <a-select
          v-model:value="form.demandType"
          class="formInput"
          placeholder="日前需求响应"
          :disabled="true"
        >
          <a-select-option value="日前需求响应">日前需求响应</a-select-option>
          <a-select-option value="日内需求响应">日内需求响应</a-select-option>
          <a-select-option value="日前无功需求响应"
            >日前无功需求响应</a-select-option
          >
        </a-select>
      </a-form-item>

      <!-- <a-form-item label="是否参与邀约" name="isParticipate">
        <a-select
          v-model:value="form.isParticipate"
          class="formInput"
          placeholder="请选择"
        >
          <a-select-option value="是">是</a-select-option>
          <a-select-option value="否">否</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="申报用户" name="declareUser">
        <a-select
          v-model:value="form.declareUser"
          class="formInput"
          placeholder="请选择"
        >
          <a-select-option value="用户A">用户A</a-select-option>
          <a-select-option value="用户B">用户B</a-select-option>
          <a-select-option value="用户C">用户C</a-select-option>
        </a-select>
      </a-form-item> -->

      <a-form-item label="分时价格" name="timeBasedPrice">
        <div class="upload-container">
          <a-upload
            v-model:file-list="form.priceFileList"
            :before-upload="beforeUpload"
            :maxCount="1"
            accept=".xlsx,.xls,.csv"
            :action="uploadUrl"
            :headers="headers"
            @change="handlePriceUploadChange"
          >
            <a-button
              class="greenpPlainBtn"
              :loading="priceImportLoading"
              size="small"
            >
              <UploadOutlined />
              点击上传
            </a-button>
            <a-button
              type="link"
              @click.stop="handleDownloadPriceTemplate"
              class="downLoadTep"
              >下载模板</a-button
            >
            <template #itemRender="{ file }">
              <div class="ant-upload-list-item-info">
                <span class="ant-upload-list-item-name">{{ file.name }}</span>
              </div>
            </template>
          </a-upload>
        </div>
      </a-form-item>

      <a-form-item label="用户调节功能" name="userAdjustFunction">
        <div class="upload-container">
          <a-upload
            v-model:file-list="form.functionFileList"
            :before-upload="beforeUpload"
            :maxCount="1"
            accept=".xlsx,.xls,.csv"
            :action="uploadUrl"
            :headers="headers"
            @change="handleFunctionUploadChange"
          >
            <a-button
              class="greenpPlainBtn"
              :loading="functionImportLoading"
              size="small"
            >
              <UploadOutlined />
              点击上传
            </a-button>
            <a-button
              type="link"
              @click.stop="handleDownloadFunctionTemplate"
              class="downLoadTep"
              >下载模板</a-button
            >
            <template #itemRender="{ file }">
              <div class="ant-upload-list-item-info">
                <span class="ant-upload-list-item-name">{{ file.name }}</span>
              </div>
            </template>
          </a-upload>
        </div>
      </a-form-item>
    </a-form>

    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          提交
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, inject } from "vue"
import { message } from "ant-design-vue"
import { UploadOutlined } from "@ant-design/icons-vue"
import storage from "@/utils/storage"

const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const $api = inject("$api")
const labelCol = { style: { width: "155px" } }

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  recordData: {
    type: Object,
    default: () => ({}),
  },
})

const emits = defineEmits(["update:visible", "refresh"])

const visible = ref(props.visible)
const loading = ref(false)
const priceImportLoading = ref(false)
const functionImportLoading = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  planName: "",
  demandType: "",
  isParticipate: "",
  declareUser: "",
  priceFileList: [],
  functionFileList: [],
})

// 表单验证规则
const rules = {
  planName: [
    { required: true, message: "请输入需求计划名称", trigger: "blur" },
  ],
  demandType: [
    { required: true, message: "请选择需求类型", trigger: "change" },
  ],
  isParticipate: [
    { required: true, message: "请选择是否参与邀约", trigger: "change" },
  ],
  declareUser: [
    { required: true, message: "请选择申报用户", trigger: "change" },
  ],
  priceFileList: [
    { required: true, message: "请上传分时价格文件", trigger: "change" },
  ],
  functionFileList: [
    { required: true, message: "请上传用户调节功能文件", trigger: "change" },
  ],
}

// 监听visible变化
watch(
  () => props.visible,
  (val) => {
    visible.value = val
    if (val && props.recordData) {
      // 根据传入的记录数据初始化表单
      form.planName = props.recordData.planName
      form.demandType = props.recordData.demandResponseType
    }
  }
)

watch(visible, (val) => {
  emits("update:visible", val)
})

// 取消
const cancel = () => {
  visible.value = false
  formRef.value?.clearValidate()
  // 重置表单
  Object.assign(form, {
    planName: "",
    demandType: "",
    isParticipate: "",
    declareUser: "",
    priceFileList: [],
    functionFileList: [],
  })
}

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const params = {
      ...form,
      recordId: props.recordData?.id,
    }

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000))

    message.success("申报成功")
    cancel()
    emits("refresh")
  } catch (error) {
    console.error("申报失败:", error)
  } finally {
    loading.value = false
  }
}

const uploadUrl = ref(`${$api.uploadAction().url}`)

// 文件上传前的处理
const beforeUpload = (file) => {
  const isValidFormat =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel" ||
    file.name.endsWith(".csv")
  if (!isValidFormat) {
    message.error("只支持上传 .xlsx, .xls, .csv 格式的文件！")
    return false
  }
}

// 分时价格文件上传变化处理
const handlePriceUploadChange = (data) => {
  priceImportLoading.value = false
  form.priceFileList = data.fileList
}

// 用户调节功能文件上传变化处理
const handleFunctionUploadChange = (data) => {
  functionImportLoading.value = false
  form.functionFileList = data.fileList
}

// 下载分时价格模板
const handleDownloadPriceTemplate = (event) => {
  event.preventDefault()
  event.stopPropagation()
  // 分时价格模板下载
  message.info("分时价格模板下载功能待实现")
}

// 下载用户调节功能模板
const handleDownloadFunctionTemplate = (event) => {
  event.preventDefault()
  event.stopPropagation()
  // 用户调节功能模板下载
  message.info("用户调节功能模板下载功能待实现")
}
</script>

<style lang="less" scoped>
.formInput {
  width: 250px;
}

.footerBar {
  text-align: center;
  margin-top: 20px;
}

:deep(.ant-form-item) {
  margin-bottom: 20px;
}

:deep(.ant-modal-header) {
  background: #1f1f1f;
  border-bottom: 1px solid #303030;
}

:deep(.ant-modal-content) {
  background: #1f1f1f;
  color: #fff;
}

:deep(.ant-modal-footer) {
  background: #1f1f1f;
  border-top: 1px solid #303030;
}

.downLoadTep {
  padding: 4px 5px 4px 10px;
}

.upload-container {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style>
